import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/widgets/video/xindong_common_video_list_ctr.dart';
import 'package:video_player/video_player.dart';

// 共用列表视频视图
class XinDongCommonListVideoWidget extends StatefulWidget {
  final String videoKey; // 视频唯一key
  final String? cover; // 封面地址
  final String videoUrl; // 视频地址
  final double aspectRatio; // 比例
  final double borderRadius; // 圆角
  final bool canFullscreen; // 能否点击全屏播放

  const XinDongCommonListVideoWidget({
    Key? key,
    required this.videoKey,
    required this.cover,
    required this.videoUrl,
    required this.aspectRatio,
    this.borderRadius = 4.0,
    this.canFullscreen = true,
  }) : super(key: key);

  @override
  State<XinDongCommonListVideoWidget> createState() => _XinDongCommonListVideoWidgetState();
}

class _XinDongCommonListVideoWidgetState extends State<XinDongCommonListVideoWidget> {
  final _videoController = XinDongCommonVideoListCtr.to;
  late VideoPlayerController _playerController;

  @override
  void initState() {
    super.initState();

    // 播放器
    _playerController = VideoPlayerController.networkUrl(Uri.parse(widget.videoUrl));
    _playerController.setLooping(true);
    _playerController.setVolume(0);
    _playerController.initialize().then((_) {
      setState(() {});
    });
  }

  @override
  void deactivate() {
    super.deactivate();
    _playerController.pause();
  }

  @override
  void dispose() {
    _playerController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AspectRatio(
      aspectRatio: widget.aspectRatio,
      child: PhysicalModel(
        color: Colors.transparent,
        borderRadius: BorderRadius.circular(widget.borderRadius),
        clipBehavior: Clip.antiAlias,
        child: GestureDetector(
          onTap: widget.canFullscreen
              ? () => _videoController.xindong_onFullScreen(
                    videoKey: widget.videoKey,
                    playerController: _playerController,
                  )
              : null,
          child: Obx(
            () {
              return _videoController.normalPlayerView(
                videoKey: widget.videoKey,
                cover: widget.cover,
                playerController: _playerController,
              );
            },
          ),
        ),
      ),
    );
  }
}
